import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile, Res, Req } from '@nestjs/common';
import { UploadModuleService } from './upload-module.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { Request, Response } from 'express';
import { join } from 'path';
import { zip } from 'compressing';

@Controller('upload')
export class UploadModuleController {
  constructor(private readonly uploadModuleService: UploadModuleService) {}
  // 上传图片
  @Post('imgs')
  @UseInterceptors(FileInterceptor('file'))
  uploadImg(@UploadedFile() file) {
    // console.log('file:', file)
    return {
      code: 0,
      msg: '上传成功',
      imgdata: file,
      url: '/uploadimgs/' + file.filename
    };
  }
  // 下载图片
  @Get('getimg')
  downloadImg(@Req() req: Request, @Res() res: Response) {
    let imgurl = join(__dirname, '../public', (req.query.url) as string);
    // console.log('getimg:', req.query, imgurl);
    if (imgurl) {
      res.download(imgurl as string);
    };
  }
  // 使用文件流的方式下载
  @Get('getimg2')
  async downloadstreamImg(@Req() req: Request, @Res() res: Response) {
    let imgurl = join(__dirname, '../public', (req.query.url) as string);
    const tarStream  = new zip.Stream()
    await tarStream.addEntry(imgurl)
    res.setHeader('Content-Type', 'application/octet-stream');
    res.setHeader(
      'Content-Disposition',  
      `attachment; filename=${(req.query.url as string).match(/\d+/)[0]}`,
    );

    // console.log('getimg2:', req.query, imgurl, (req.query.url as string).match(/\d+/)[0]);
    tarStream.pipe(res)
  }
}
